const md5Password = require("../utils/password-handle");
const userService = require("../service/user.service");
const errorType = require("../constants/error-types");
const verifyLogin = async (ctx, next) => {
  console.log(ctx.request.body, "verifyLogin");
  const { name, password } = ctx.request.body;
  // 验证帐号密码是否为空
  try {
    if (!name || !password) {
      const error = new Error(errorType.NAME_AND_PASSWORD_IS_REQUIRED);
      return ctx.app.emit("error", error, ctx);
    }
    const result = await userService.getUserByName(name);
    if (!result) {
      const error = new Error(errorType.USER_IS_NOT_EXISTS);
      return ctx.app.emit("error", error, ctx);
    }
    ctx.user = result;
    if (result.password !== md5Password(password)) {
      const error = new Error(errorType.PASSWORD_IS_INCORRECT);
      return ctx.app.emit("error", error, ctx);
    }
  } catch (error) {
    console.log(error);
  }
  await next();
};

module.exports = {
  verifyLogin,
};
